﻿using System.Text.Json.Serialization;
using BCore.Identity.Users.Caching;
using Core.Caching;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Users.Features.Queries.GetRoleById;

public class GetUserRoleByIdQuery : ICacheableRequest<Result<IEnumerable<Guid>>>
{
    public Guid UserId { get; set; }

    /// <summary>
    /// 缓存键
    /// </summary>
    [JsonIgnore]
    public string CacheKey => UsersCacheKey.GetUserRolesCacheKey(UserId.ToString());
    /// <summary>
    /// 缓存选项
    /// </summary>
    [JsonIgnore]
    public IEnumerable<string> Tags => UsersCacheKey.Tags!;
}

public class GetUserRoleByIdQueryHandler(
    IIdentityDbContext context) : IRequestHandler<GetUserRoleByIdQuery, Result<IEnumerable<Guid>>>
{

    public async Task<Result<IEnumerable<Guid>>> Handle(GetUserRoleByIdQuery request, CancellationToken cancellationToken)
    {
        return await Result<IEnumerable<Guid>>
            .SucceedAsync(await context.UserRoles
            .Where(x => x.UserId == request.UserId)
            .Select(x => x.RoleId)
            .ToListAsync(cancellationToken));
    }
}
